# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(plyr)
library(magrittr)
library(ropls)
library(optparse)
library(tidyverse)
library(jsonlite)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

configGet <- function(configData, key) {
  configData %>%
    filter(arg == key) %>%
    .$value
}

option_list <- list(
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--cc", default = "calculate_config.json", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

configJson <- fromJSON(opt$cc)
minQ2Y <- configJson$q2Y %>%
  as.numeric()
maxQ2YB <- configJson$q2YB %>%
  as.numeric()

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote")) %>%
  mutate(ClassNote = as.character(ClassNote))

parent <- paste0("./")
createWhenNoExist(parent)
perFileName <- paste0(parent, "/OPLSDA_Permutation.csv")

plotData <- read.csv(perFileName, header = T)

fixData <- plotData %>%
  filter(Similarity == 1) %>%
  head(1)
offsetPlotData <- plotData %>%
  mutate(Similarity = Similarity - 1, Q2 = Q2 - fixData$Q2, R2Y = R2Y - fixData$R2Y)

lmRs <- lm(Q2 ~ Similarity + 0, offsetPlotData)
q2A <- coef(lmRs)["Similarity"]
q2B <- fixData$Q2 - q2A * 1

lmRs <- lm(R2Y ~ Similarity + 0, offsetPlotData)
r2A <- coef(lmRs)["Similarity"]
r2B <- fixData$R2Y - r2A * 1

q2Rank <- plotData %>%
  arrange(desc(Q2)) %>%
  filter(Q2 >= fixData$Q2) %>%
  nrow()

q2P <- q2Rank / 1000

R2Rank <- plotData %>%
  arrange(desc(R2Y)) %>%
  filter(R2Y >= fixData$R2Y) %>%
  nrow()

R2P <- R2Rank / 1000

tbf <- tibble(` ` = c("Q2", "R2"), `vertical intercept` = c(q2B, r2B), slope = c(q2A, r2A), rank = c(q2Rank, R2Rank),
              p = c(q2P, R2P))

write_csv(tbf, str_c(parent, "/fitted_curve_parameter.csv"))

q2 <- fixData$Q2
valid <- if (q2 >= minQ2Y & q2B <= maxQ2YB) {
  T
}else F
validDf <- tibble(valid = c(valid))
write_tsv(validDf, "valid.txt")






